package com.viettel.pon.Tabs;

import java.util.ArrayList;

import org.apache.log4j.Logger;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.viettel.pon.R;
import com.viettel.pon.adapter.MyListAdapter;
import com.viettel.pon.common.DataBaseHelper;
import com.viettel.pon.common.GlobalClass;
import com.viettel.pon.form.InfomationForm;
import com.viettel.pon.main.MainActivity;

public class TimeListActivity extends Fragment {
	private Logger mLog;
	private ListView lvListTime;
	private TextView txtListTime;
	Button btnInsertTrack;
	Button btnCancelTrack;
	EditText edtTrackName;
	EditText edtTrackDescription;
	int width;
	int timeListId;
	private RelativeLayout layoutToReplaceView;

	private Context _context;
	DataBaseHelper db;
	private ArrayList<InfomationForm> lstTime = new ArrayList<InfomationForm>();
	View rootView;
	private GlobalClass _glb;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mLog = Logger.getLogger(TimeListActivity.class);
		rootView = inflater.inflate(R.layout.activity_list_time, container,
				false);
		_context = getActivity().getApplicationContext();
		_glb = (GlobalClass) _context.getApplicationContext();
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(displaymetrics);
		width = displaymetrics.widthPixels / 10;
		TableRow.LayoutParams params1 = new TableRow.LayoutParams(width * 10,
				android.view.ViewGroup.LayoutParams.FILL_PARENT);
		String myTag = getTag();
		//((MainActivity) getActivity()).setTabTrack(myTag);

		db = new DataBaseHelper(_context);
		lvListTime = (ListView) rootView.findViewById(R.id.lvListTime);
		//clear cache
		lvListTime.invalidateViews();
		
		txtListTime = (TextView) rootView.findViewById(R.id.txtListTime);
		layoutToReplaceView = (RelativeLayout) rootView
				.findViewById(R.id.layoutToReplaceView);

		lvListTime.setLayoutParams(params1);
		txtListTime.setLayoutParams(params1);
		getActivity().getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		lstTime = db.getAllTimeStop();
		if (lstTime.size() > 0) {
			ArrayAdapter<InfomationForm> adapter = new MyListAdapter(_context,
					lstTime, width);
			lvListTime.setAdapter(adapter);
		}

		lvListTime.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				mLog.info("Select Track");
				InfomationForm item = (InfomationForm) arg0
						.getItemAtPosition(arg2);
				Log.e("id", String.valueOf(item.getId()));
				_glb.setTimeListId(item.getId());
				_glb.setFlag(2);
				String tabTrack = ((MainActivity) getActivity()).getTabView();
				ViewActivity fragmentView = (ViewActivity) getActivity()
						.getSupportFragmentManager()
						.findFragmentByTag(tabTrack);
				fragmentView.reloadMap(item.getId());
				Log.e("timeListId:     ", String.valueOf(item.getId()));
				((MainActivity) getActivity()).actionBar
						.setSelectedNavigationItem(0);
			}
		});
		
		lvListTime.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				mLog.info("Delete Track start");
				InfomationForm item = (InfomationForm) arg0
						.getItemAtPosition(arg2);
				Log.e("id", String.valueOf(item.getId()));
				timeListId=item.getId();
				dlgConfirmDeleteTimeList().show();
				return true;
			}
		});

		return rootView;
	}

	@Override
	public void onResume() {
		super.onResume();
		lstTime = db.getAllTimeStop();
		if (lstTime.size() > 0) {
			ArrayAdapter<InfomationForm> adapter = new MyListAdapter(_context,
					lstTime, width);
			adapter.notifyDataSetChanged();
			lvListTime.setAdapter(adapter);
		}
	}

	/*
	 * cap nhat list track
	 */
	public void updateView() {
		lstTime = db.getAllTimeStop();
		if (lstTime.size() > 0) {
			ArrayAdapter<InfomationForm> adapter = new MyListAdapter(_context,
					lstTime, width);
			adapter.notifyDataSetChanged();
			lvListTime.setAdapter(adapter);
		}
	}

	/*
	 * Tao menu
	 */

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// Inflate the menu items for use in the action bar
		inflater.inflate(R.menu.menu, menu);

		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		// same as using a normal menu
		switch (item.getItemId()) {

		case R.id.actionAddTractList:
			showPopup();
			break;
		}

		return true;

	}

	private void showPopup() {
		LayoutInflater layoutInflater = (LayoutInflater) getActivity()
				.getBaseContext().getSystemService(
						Context.LAYOUT_INFLATER_SERVICE);
		View popupView = layoutInflater
				.inflate(R.layout.insert_tractlist, null);
		btnInsertTrack = (Button) popupView.findViewById(R.id.btnInsertTrack);
		btnCancelTrack = (Button) popupView.findViewById(R.id.btnCancelTrack);
		edtTrackName = (EditText) popupView.findViewById(R.id.edtTrackName);
		edtTrackDescription = (EditText) popupView
				.findViewById(R.id.edtTrackDescription);
		final PopupWindow popupWindow = new PopupWindow(popupView,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.update();
		btnCancelTrack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mLog.info("Cancel Insert Track");
				popupWindow.dismiss();
			}
		});
		btnInsertTrack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mLog.info("Insert Track start");
				String trackName = edtTrackName.getText().toString().trim();
				String trackNote = edtTrackDescription.getText().toString()
						.trim();
				if (db.insertTimeStopList("0", "0", trackName, trackNote) == 0) {
					mLog.info("Insert Track success");
					Log.e("insert Track List", "success");
					// String tabTrack = getTabTrack();
					// TimeListActivity fragmentSearch = (TimeListActivity)
					// getSupportFragmentManager()
					// .findFragmentByTag(tabTrack);
					// fragmentSearch.updateView();
					updateView();
					popupWindow.dismiss();
				} else {
					mLog.info("Insert Track fail");
					Log.e("insert Track List", "fail");
				}
			}
		});
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	
	 public AlertDialog dlgConfirmDeleteTimeList() {
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle("Thông báo");
			builder.setMessage("Bạn có chắc chắn muốn xóa bản ghi này?");
			builder.setCancelable(false);
			builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Log.e("delete colcode:   ", String.valueOf(_glb.getColId()));
					db.onDeleteByIdTimeTable(timeListId, "POLES_LIST");
					db.onDeleteByIdTimeTable(timeListId, "HOUSE_LIST");
					db.onDeleteByIdTimeTable(timeListId, "POSITION_LIST");
					db.onDeleteByIdTimeTable(timeListId, "PLACE_LIST");
					if(db.deleteTableById(timeListId, "LIST_TIME_STOP")==1){
						createDialogErrorNotReturn("Xóa thành công!").show();
						mLog.info("Delete Track success");
					}else{
						createDialogErrorNotReturn("Xóa không thành công!").show();
						mLog.info("Delete Track fail");
					}
					
				}
			});
			builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				
				}
			});
			AlertDialog dialog = builder.create();
			return dialog;
		}
	 public AlertDialog createDialogErrorNotReturn(String msg) {
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle("Thông báo");
			builder.setMessage(msg);
			builder.setCancelable(false);
		
			builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					updateView();
				}
			});
			AlertDialog dialog = builder.create();
			return dialog;
		}
	    
}